﻿/*-------------------------------------------------------------------------
* 命名空间: XrayDirection.ViewModels/ChangeNextRecipeViewModel
* 类       名: ChangeNextRecipeViewModel
* 功      能:  TD
* 时      间:  2024/2/24 15:08:41
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using SiliconSelect.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using XrayDirection.Common;
using XrayDirection.DAL;
using XrayDirection.DAL.DataEntity;
using XrayDirection.DAL.LocalDataAccess;
using XrayDirection.Extensions;
using XrayDirection.HelperManager;
using XrayDirection.Services;
using XrayDirection.Views;

namespace XrayDirection.ViewModels
{
    public class ChangeNextRecipeViewModel : BindableBase
    {
        private IContainerProvider _containerProvider;
        private IWindowService _windowService;
        private readonly IEventAggregator _eventAggregator;

        public ChangeNextRecipeViewModel(IContainerProvider containerProvider, IWindowService windowService, IEventAggregator eventAggregator)
        {
            _containerProvider = containerProvider;
            _windowService = windowService;
            _eventAggregator = eventAggregator;
            RefreshInputPlanOrders();
            DeleteRecipeCommand = new DelegateCommand(DoDeleteRecipeTask);
            ChangeRecipeCommand = new DelegateCommand(DoChangeRecipeTask);
            CancelChangeCommand = new DelegateCommand(DoCancelChangeTask);
        }

        public void PublishRecipeChangeEvent()
        {
            _eventAggregator.GetEvent<RecipeChangeEvent>().Publish(string.Empty);
        }

        private void DoCancelChangeTask()
        {
            // 直接关闭窗口即可
            _windowService.CloseWindow(nameof(ChangeNextRecipeView));
        }

        // 切换工单,切换工单的时候要注意一点,要先选中工单.
        private void DoChangeRecipeTask()
        {
            if (SelectedIndex != -1)
            {
                var orderUsed = InputPlanOrders[SelectedIndex];
                //OrderEntity order = new OrderEntity()
                //{
                //    RecipeName = orderUsed.RecipeName,
                //    CreateTime = DateTimeHelper.GetTimeNowForSql(),
                //    LongLengthX = orderUsed.LongLengthX,
                //    ShortLengthY = orderUsed.ShortLengthY,
                //    FrontEdgeDisD = orderUsed.FrontEdgeDisD,
                //    DirectHoleDisF = orderUsed.DirectHoleDisF,
                //    MoveOffset = orderUsed.MoveOffset,
                //    OkCount = 0,
                //    FailCount = 0,
                //    UpdateTime = DateTimeHelper.GetTimeNowForSql(),
                //};
                //var addRes = OrderAccess.AddOrderWithIdBack(order);
                if (true)
                {
                    // 切换后的工单Id,先更新到WorkingInfo中去.
                    var workingInfoRes = WorkingInfoAccess.GetWorkingInfos();
                    if (workingInfoRes.State)
                    {
                        var oldWorkingInfo = workingInfoRes.Data![0];
                        // 找到了当前作业的工单信息,然后更新它的内容
                        WorkingInfoEntity workingInfoNew = new WorkingInfoEntity()
                        {
                            Id = oldWorkingInfo.Id,
                            WorkingRecipeId = orderUsed.Id,
                            WorkingRecipeName = orderUsed.RecipeName,
                            BorderIndex = 1,
                            BorderIndexMax = oldWorkingInfo.BorderIndexMax,
                            CreateTime = DateTimeHelper.GetTimeNowForSql(),
                            UpdateTime = DateTimeHelper.GetTimeNowForSql(),
                        };
                        var updateRes = WorkingInfoAccess.UpdateWorkingInfo(workingInfoNew);
                        if (!updateRes.State)
                        {
                            MessageProvider.ShowError(updateRes.Message!, "数据库更新失败提示");
                        }
                        {
                            orderUsed.OkCount = 0;
                            orderUsed.FailCount = 0;
                            orderUsed.Count = 0;
                            OrderAccess.UpdateOrder(orderUsed);// 清除工单的计数数据
                            PublishRecipeChangeEvent();
                            // 更新成功之后,去刷新一下工单,然后将当前的工单删除.
                            _containerProvider.Resolve<IndexViewModel>().RefreshWorkingInfo();
                            // 工单对应目录创建,切换工单的时候需要做的事情.
                            _containerProvider.Resolve<IndexViewModel>().InitImageDir();
                            // 关闭当前窗口
                            _windowService.CloseWindow(nameof(ChangeNextRecipeView));
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("数据库操作异常" + workingInfoRes.Message!);
                    }
                }
            }
            else
            {
                MessageProvider.ShowInfo("请选中你要切换的工单!", "工单切换提示");
            }
        }

        // 删除工单
        private void DoDeleteRecipeTask()
        {
            if (SelectedIndex != -1)
            {
                int deleteId = InputPlanOrders[SelectedIndex].Id;
                var result = OrderAccess.DeleteOrderById(deleteId);
                if (result.State)
                {
                    RefreshInputPlanOrders();
                }
                else
                {
                    MessageProvider.ShowError(result.Message!, "删除失败提示框");
                }
            }
        }

        public DelegateCommand DeleteRecipeCommand { get; private set; }
        public DelegateCommand ChangeRecipeCommand { get; private set; }
        public DelegateCommand CancelChangeCommand { get; private set; }


        // 从数据库中刷新切换工单的那个表.
        public void RefreshInputPlanOrders()
        {
            var result = OrderAccess.GetOrders();
            if (result.State)
            {
                InputPlanOrders.Clear();
                foreach (var order in result.Data!)
                {
                    InputPlanOrders.Add(order);
                }
            }
            else
            {
                MessageProvider.ShowError(result.Message!, "数据库操作失败");
            }
            if (InputPlanOrders.Count > 0)
            {
                SelectedIndex = 0;
            }
            else
            {
                SelectedIndex = -1;
            }
        }

        /// <summary>
        /// 选中某一行,如果不为空,就默认选中第一行.
        /// </summary>
        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set
            {
                selectedIndex = value;
                RaisePropertyChanged();
            }
        }


        private ObservableCollection<OrderEntity> inputPlanOrders = new ObservableCollection<OrderEntity>();

        public ObservableCollection<OrderEntity> InputPlanOrders
        {
            get { return inputPlanOrders; }
            set
            {
                inputPlanOrders = value;
                RaisePropertyChanged();
            }
        }

    }
}
